﻿using System;
using System.Windows.Forms;
using System.Drawing;
using System.Threading.Tasks;
using System.Collections.Generic;
using Newtonsoft.Json.Linq;

namespace 云起停车_岗亭端
{
    public partial class Form3 : Form
    {
        public static Dictionary<string, Form3> instance = new Dictionary<string, Form3>();
        private int fontZise;
        private string message;
        private Barrier barrier;
        private string msgtype;
        private string plate_number;
        private int records_id;
        private int recovery_id;
        private int trigger_id;
        //打开时间
        private int hide_time;
        private int display_time;

        private Form3(Barrier barrier,int hide_time)
        {
            InitializeComponent();
            this.barrier = barrier;
            this.StartPosition = FormStartPosition.Manual;
            //设置窗体在屏幕中间的一个随机位置，确保多个winform不重叠
            Random random = new Random();
            int maxwidth=(Screen.PrimaryScreen.WorkingArea.Width-this.Width)/2;
            int maxheight = (Screen.PrimaryScreen.WorkingArea.Height-this.Height)/2;
            int x = random.Next(maxwidth-100, maxwidth+100);
            int y = random.Next(maxheight-100, maxheight+100);
            //设置窗体位置
            this.Location = new Point(x, y);
            if (hide_time > 0)
            {
                this.hide_time = hide_time * 60; //转换为秒
            }
            else
            {
                this.hide_time = 0; //默认不自动关闭
            }
            //设置自动关闭时间
            Timer timer = new Timer();
            timer.Interval = 1000;
            timer.Tick += timer_Tick;
            timer.Start();
        }

        private void timer_Tick(object sender, EventArgs e)
        {
            int timestamp = (int)DateTimeOffset.UtcNow.ToUnixTimeSeconds();

            if (this.hide_time > 0 && timestamp - this.display_time >= this.hide_time && this.Visible)
            {
                this.Hide();
            }
        }

        public static Form3 getInstance(Barrier barrier,int fontZise,int hide_time)
        {
            if (instance.ContainsKey(barrier.serialno))
            {
                Form3 form3 = instance[barrier.serialno];
                return form3;
            }
            else
            {
                Form3 form3 = new Form3(barrier, hide_time);
                form3.fontZise = fontZise;
                form3.MaximizeBox = false;
                form3.MinimizeBox = false;
                instance.Add(barrier.serialno, form3);
                return form3;
            }
        }

        public static void CloseFormByPlatenumber(string plate_number)
        {
            foreach (var item in instance)
            {
                Form3 form3 = item.Value;
                if (form3.plate_number!=null && form3.plate_number.Equals(plate_number))
                {
                    form3.Hide();
                    break;
                }
            }
        }

        public Form3 SetPlateNumber(string plate_number)
        { 
            this.plate_number = plate_number;
            return this;
        }
        
        public Form3 SetMessage(string message)
        { 
            this.message = message;
            return this;
        }

        public Form3 SetRecordsId(int records_id)
        {
            this.records_id = records_id;
            return this;
        }

        public Form3 SetTriggerId(int trigger_id)
        {
            this.trigger_id = trigger_id;
            return this;
        }

        public Form3 SetRecoveryId(int recovery_id)
        {
            this.recovery_id = recovery_id;
            return this;
        }

        public Form3 SetOptions(string[] options=null)
        {
            this.comboBox1.Items.Clear();
            if (this.barrier.barrier_type.Equals("entry"))
            {
                this.comboBox1.Items.Add("现金收费");
            }
            if(options != null && options.Length>0)
            {
                foreach (string option in options)
                {
                    this.comboBox1.Items.Add(option);
                }
            }
            this.comboBox1.Items.Add("填写原因");
            this.comboBox1.SelectedIndex = 0;
            return this;
        }


        public void Display(string msgtype,string imgurl)
        {
            Dictionary<string, string> title = new Dictionary<string, string>() {
                {"pay","车主支付提醒"},
                {"manual","手动入场提醒"},
                {"recovery","欠费追缴提醒"},
                {"open","手动开闸"},
            };
            this.msgtype = msgtype;
            //设置窗体标题
            this.Text = title[msgtype];
            this.panel1.Controls.Clear();
            //为panel1添加一个Label控件，内容为message
            Label label = new Label() { 
                Text = message,
                Font = new System.Drawing.Font("微软雅黑", fontZise),
                Dock = DockStyle.Fill,
                AutoSize = false,
                TextAlign = System.Drawing.ContentAlignment.MiddleLeft,
                MaximumSize = new System.Drawing.Size(this.panel1.Width, 0),
                AutoEllipsis = false
            };
            this.panel1.Controls.Add(label);
            this.ChangeFontSize();
            _ = Task.Run(() => LoadImg(imgurl));
            //打开窗体的时间戳
            int timestamp = (int)DateTimeOffset.UtcNow.ToUnixTimeSeconds();
            this.display_time = timestamp;
            this.Show();
        }

        private async void LoadImg(string imgurl)
        {
            //清除历史的图片
            if (this.pictureBox1.Image != null)
            {
                this.pictureBox1.Image.Dispose();
                this.pictureBox1.Image = null;
            }
            //加载图片
            Image image = await Utils.LoadImageFromUrlAsync(imgurl);
            this.pictureBox1.Image=image;
        }

        private void ChangeFontSize()
        {
            this.button1.Font = new System.Drawing.Font("微软雅黑", fontZise);
            this.button2.Font = new System.Drawing.Font("微软雅黑", fontZise);
            this.label1.Font = new System.Drawing.Font("微软雅黑", fontZise);
            this.panel1.Font = new System.Drawing.Font("微软雅黑", fontZise);
            this.comboBox1.Font = new System.Drawing.Font("微软雅黑", fontZise);
            this.richTextBox1.Font = new System.Drawing.Font("微软雅黑", fontZise);
            this.richTextBox1.Text = "请输入开闸理由";
            this.richTextBox1.ForeColor = System.Drawing.Color.Gray;
            //如果richTextBox1的选项大于1，则设置为只读
            if (this.comboBox1.Items.Count > 1)
            {
                this.richTextBox1.Enabled = false;
            }
        }

        private void richTextBox1_Enter(object sender, System.EventArgs e)
        {
            if (this.richTextBox1.Text == "请输入开闸理由")
            {
                this.richTextBox1.Text = "";
                this.richTextBox1.ForeColor = System.Drawing.Color.Black;
            }
        }

        private void richTextBox1_Leave(object sender, System.EventArgs e)
        {
            if (this.richTextBox1.Text == "")
            {
                this.richTextBox1.Text = "请输入开闸理由";
                this.richTextBox1.ForeColor = System.Drawing.Color.Gray;
            }
        }

        private void comboBox1_SelectedValueChanged(object sender, EventArgs e)
        {
            if (comboBox1.Text == "填写原因") {
                this.richTextBox1.Enabled = true;
            }
            else
            {
                this.richTextBox1.Enabled = false;
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            //关闭窗体
            this.Hide();
        }

        private async void button1_Click(object sender, EventArgs e)
        {
            if (this.comboBox1.Text.Equals("填写原因") && (this.richTextBox1.Text.Trim().Equals("") || this.richTextBox1.Text.Equals("请输入开闸理由")))
            {
                MessageBox.Show("请输入开闸理由");
                return;
            }
            JObject obj = new JObject();
            obj.Add("remark", this.comboBox1.Text);
            obj.Add("diy_remark", this.richTextBox1.Text);
            if (this.records_id > 0)
            {
                obj.Add("records_id", this.records_id);
            }
            if (this.trigger_id > 0)
            {
                obj.Add("trigger_id", this.trigger_id);
            }
            if (this.recovery_id > 0)
            {
                obj.Add("recovery_id", this.recovery_id);
            }
            obj.Add("barrier_id", this.barrier.id);
            Response response = await Utils.PostAsync("sentrybox/index/open", obj, this);
            if (null == response)
            {
                return;
            }
            this.Hide();
        }

        private void Form3_FormClosing(object sender, FormClosingEventArgs e)
        {
            //取消窗体关闭事件
            e.Cancel = true;
            this.Hide();
        }
    }
}
